using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using LeisureCenter.Api;

namespace LeisureCenter.WebUI
{
    internal class WebUserInterfaceManager
    {
        #region private fields

        private HttpListener _httpListener;

        #endregion

        #region private methods

        private void HandleListenerGetContext(IAsyncResult result)
        {
            // start listening again
            _httpListener.BeginGetContext(HandleListenerGetContext, _httpListener);

            // Call EndGetContext to complete the asynchronous operation.
            HttpListenerContext context = _httpListener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            HandleRequest(request, response);
        }

        private void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
        {
            switch (request.Url.AbsolutePath.ToLower())
            {
                case "/command":
                    HandleCommand(request, response);
                    break;
                default:
                    HandleDefault(request, response);
                    break;
            }
        }

        private void HandleDefault(HttpListenerRequest request, HttpListenerResponse response)
        {
            // Obtain a response object.
            // Construct a response.
            string responseString = "<HTML><BODY> Hello world!<a href=\"/command?name=stop\">Stop</a></BODY></HTML>";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
        }

        private void HandleCommand(HttpListenerRequest request, HttpListenerResponse response)
        {
            byte[] buffer;
            string responseString;
            string commandName = request.QueryString["name"];

            LeisureCenterCommand command;
            try
            {
                command = (LeisureCenterCommand)Enum.Parse(typeof(LeisureCenterCommand), commandName, true);
            }
            catch (ArgumentException)
            {
                // Obtain a response object.
                // Construct a response.
                responseString = "Error: Unknown command!";
                buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                using (System.IO.Stream output = response.OutputStream)
                {
                    output.Write(buffer, 0, buffer.Length);
                }
                return;
            }

            Program.LeisureCenterInstance.CommandsManager.EnqueueCommand(command);

            // Obtain a response object.
            // Construct a response.
            responseString = "Stopped!";
            buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
        }

        #endregion

        #region public members

        public void Initialize()
        {
            if (Program.LeisureCenterInstance.Settings.WebUI.Enabled)
            {
                _httpListener = new HttpListener();
                _httpListener.Prefixes.Add(string.Format("http://+:{0}/", Program.LeisureCenterInstance.Settings.WebUI.Port));
                _httpListener.Start();
                _httpListener.BeginGetContext(HandleListenerGetContext, _httpListener);
            }
        }

        #endregion
    }
}
